package net.zio.kamenriderzioaddon.entity;

import net.minecraft.world.entity.monster.Monster;
import org.jetbrains.annotations.NotNull;
import software.bernie.geckolib3.util.GeckoLibUtil;
import software.bernie.geckolib3.core.manager.AnimationFactory;
import software.bernie.geckolib3.core.manager.AnimationData;
import software.bernie.geckolib3.core.event.predicate.AnimationEvent;
import software.bernie.geckolib3.core.controller.AnimationController;
import software.bernie.geckolib3.core.builder.ILoopType.EDefaultLoopTypes;
import software.bernie.geckolib3.core.builder.AnimationBuilder;
import software.bernie.geckolib3.core.PlayState;
import software.bernie.geckolib3.core.IAnimatable;

import net.zio.kamenriderzioaddon.init.KamenRiderZioAddonModEntities;

import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.network.PlayMessages;
import net.minecraftforge.network.NetworkHooks;

import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.Level;
import net.minecraft.world.entity.ai.goal.target.HurtByTargetGoal;
import net.minecraft.world.entity.ai.goal.RandomStrollGoal;
import net.minecraft.world.entity.ai.goal.RandomLookAroundGoal;
import net.minecraft.world.entity.ai.goal.MeleeAttackGoal;
import net.minecraft.world.entity.ai.goal.FloatGoal;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.SpawnPlacements;
import net.minecraft.world.entity.Pose;
import net.minecraft.world.entity.MobType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EntityDimensions;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.TamableAnimal;
import net.minecraft.world.entity.AgeableMob;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.Difficulty;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.player.Player;


public class GeizCompleteSpecialeffectsEntity extends TamableAnimal implements IAnimatable {
	public static final EntityDataAccessor<Boolean> SHOOT = SynchedEntityData.defineId(GeizCompleteSpecialeffectsEntity.class, EntityDataSerializers.BOOLEAN);
	public static final EntityDataAccessor<String> ANIMATION = SynchedEntityData.defineId(GeizCompleteSpecialeffectsEntity.class, EntityDataSerializers.STRING);
	public static final EntityDataAccessor<String> TEXTURE = SynchedEntityData.defineId(GeizCompleteSpecialeffectsEntity.class, EntityDataSerializers.STRING);
	private AnimationFactory factory = GeckoLibUtil.createFactory(this);
	private boolean swinging;
	private boolean lastloop;
	private long lastSwing;
	public String animationprocedure = "empty";

	/**
	 * 	实体初始化
	 *
     * @param packet 实体初始化数据包
     * @param world 世界
     */
	public GeizCompleteSpecialeffectsEntity(PlayMessages.SpawnEntity packet, Level world) {
		this(KamenRiderZioAddonModEntities.GEIZ_COMPLETE_SPECIALEFFECTS.get(), world);
	}

	/**
	 * 	实体初始化
	 *
	 * @param type 实体类型
	 * @param world 世界
	 */
	public GeizCompleteSpecialeffectsEntity(EntityType<GeizCompleteSpecialeffectsEntity> type, Level world) {
		super(type, world);
		xpReward = 0;
		// 禁用AI
		setNoAi(true);
//		// 无重力
//		setNoGravity(true);
		// 无敌
		setInvulnerable(true);
	}

	// 定义实体数据
	@Override
	protected void defineSynchedData() {
		super.defineSynchedData();
		this.entityData.define(SHOOT, false);
		this.entityData.define(ANIMATION, "undefined");
		this.entityData.define(TEXTURE, "geiz_specialeffects.geo");
	}

	// 设置实体渲染
	public void setTexture(String texture) {
		this.entityData.set(TEXTURE, texture);
	}

	// 获取实体渲染
	public String getTexture() {
		return this.entityData.get(TEXTURE);
	}

	// 实体渲染
	@Override
	public @NotNull Packet<?> getAddEntityPacket() {
		return NetworkHooks.getEntitySpawningPacket(this);
	}

	@Override
	protected void registerGoals() {
		super.registerGoals();
		this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.2, false) {
			@Override
			protected double getAttackReachSqr(@NotNull LivingEntity entity) {
				return this.mob.getBbWidth() * this.mob.getBbWidth() + entity.getBbWidth();
			}
		});
		this.goalSelector.addGoal(2, new RandomStrollGoal(this, 1));
		this.targetSelector.addGoal(3, new HurtByTargetGoal(this));
		this.goalSelector.addGoal(4, new RandomLookAroundGoal(this));
		this.goalSelector.addGoal(5, new FloatGoal(this));
	}

	// 特效绑定
	@Override
	public void tick() {
		super.tick();

		// 获取绑定的玩家实体
		Player player = (Player) this.getOwner();

		if (player != null) {
			// 保持与玩家相同位置和旋转
			double verticalOffset = 0.0; // 地面
			this.setPos(player.getX(), player.getY() + verticalOffset, player.getZ());

			// 同步身体旋转角度
			this.setYRot(player.getYRot());
			this.yBodyRot = player.yBodyRot;
			this.yBodyRotO = player.yBodyRotO;


			// 同步视觉旋转
			this.setRot(player.getYRot(), player.getXRot());

			// 强制同步旋转数据到客户端
			this.setOnGround(player.isOnGround());
		}

		// 如果玩家不存在或离线，移除实体
		if (player == null || !player.isAlive()) {
			this.discard();
		}
	}

	// 禁用推动
	@Override
	public boolean isPushable() {
		return false;
	}

	// 禁用碰撞
	@Override
	public boolean canBeCollidedWith() {
		return false;
	}

	//	禁用被其他实体推动
	@Override
	public @NotNull MobType getMobType() {
		return MobType.UNDEFINED;
	}

	// 禁用推动其他实体
	@Override
	protected void doPush(@NotNull Entity entityIn) {
		super.doPush(entityIn);
	}

	// 禁用受伤音效
	@Override
	public SoundEvent getHurtSound(@NotNull DamageSource ds) {
		return ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation("entity.generic.hurt"));
	}

	// 禁用死亡音效
	@Override
	public SoundEvent getDeathSound() {
		return ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation("entity.generic.death"));
	}

	//自动移除逻辑
	@Override
	public void baseTick() {
		super.baseTick();
		this.refreshDimensions();
	}

	// 定义实体尺寸
	@Override
	public @NotNull EntityDimensions getDimensions(@NotNull Pose p_33597_) {
		return super.getDimensions(p_33597_).scale((float) 1);
	}

	// 禁用繁殖
	@Override
	public AgeableMob getBreedOffspring(@NotNull ServerLevel serverWorld, @NotNull AgeableMob ageable) {
		GeizCompleteSpecialeffectsEntity retval = KamenRiderZioAddonModEntities.GEIZ_COMPLETE_SPECIALEFFECTS.get().create(serverWorld);
        if (retval != null) {
            retval.finalizeSpawn(serverWorld, serverWorld.getCurrentDifficultyAt(retval.blockPosition()), MobSpawnType.BREEDING, null, null);
        }
        return retval;
	}

	// 定义实体生成条件
	public static void init() {
		SpawnPlacements.register(KamenRiderZioAddonModEntities.GEIZ_COMPLETE_SPECIALEFFECTS.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES,
				(entityType, world, reason, pos, random) -> (world.getDifficulty() != Difficulty.PEACEFUL && Monster.isDarkEnoughToSpawn(world, pos, random) && Mob.checkMobSpawnRules(entityType, world, reason, pos, random)));
	}

	// 构建实体属性
	public static AttributeSupplier.Builder createAttributes() {
		AttributeSupplier.Builder builder = Mob.createMobAttributes();
		builder = builder.add(Attributes.MOVEMENT_SPEED, 0.3);
		builder = builder.add(Attributes.MAX_HEALTH, 10);
		builder = builder.add(Attributes.ARMOR, 0);
		builder = builder.add(Attributes.ATTACK_DAMAGE, 3);
		builder = builder.add(Attributes.FOLLOW_RANGE, 16);
		return builder;
	}

	// 定义动画
	private <E extends IAnimatable> PlayState movementPredicate(AnimationEvent<E> event) {
		if (this.animationprocedure.equals("empty")) {
			event.getController().setAnimation(new AnimationBuilder().addAnimation("geiz_complete", EDefaultLoopTypes.LOOP));
			return PlayState.CONTINUE;
		}
		return PlayState.STOP;
	}

	// 定义动画
	private <E extends IAnimatable> PlayState procedurePredicate(AnimationEvent<E> event) {
		boolean loop = false;
		if (!loop && this.lastloop) {
			this.lastloop = false;
			event.getController().setAnimation(new AnimationBuilder().addAnimation(this.animationprocedure, EDefaultLoopTypes.PLAY_ONCE));
			event.getController().clearAnimationCache();
			return PlayState.STOP;
		}
		if (!this.animationprocedure.equals("empty") && event.getController().getAnimationState().equals(software.bernie.geckolib3.core.AnimationState.Stopped)) {
			if (!loop) {
				event.getController().setAnimation(new AnimationBuilder().addAnimation(this.animationprocedure, EDefaultLoopTypes.PLAY_ONCE));
				if (event.getController().getAnimationState().equals(software.bernie.geckolib3.core.AnimationState.Stopped)) {
					this.animationprocedure = "empty";
					event.getController().markNeedsReload();
				}
			} else {
				event.getController().setAnimation(new AnimationBuilder().addAnimation(this.animationprocedure, EDefaultLoopTypes.LOOP));
				this.lastloop = true;
			}
		}
		return PlayState.CONTINUE;
	}

	// 禁用死亡动画
	@Override
	protected void tickDeath() {
		this.discard();
	}

	// 同步动画
	public String getSyncedAnimation() {
		return this.entityData.get(ANIMATION);
	}

	// 定义动画
	public void setAnimation(String animation) {
		this.entityData.set(ANIMATION, animation);
	}

	// 定义动画控制器
	@Override
	public void registerControllers(AnimationData data) {
		data.addAnimationController(new AnimationController<>(this, "movement", 4, this::movementPredicate));
		data.addAnimationController(new AnimationController<>(this, "procedure", 4, this::procedurePredicate));
	}

	// 定义动画工厂
	@Override
	public AnimationFactory getFactory() {
		return this.factory;
	}
}